package com.woniuxy.ticketfile.controller;

import com.woniuxy.commnes.entity.ResponseResult;
import com.woniuxy.ticketfile.eneity.ConstantProperties;
import com.woniuxy.ticketfile.util.AliyunOSSUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/oss")
@Slf4j
public class UploadController {
    @Autowired
    private AliyunOSSUtil aliyunOSSUtil;
    @Autowired
    private ConstantProperties constantProperties;

//    @GetMapping("/toUploadBlog")
//    public String toUploadBlog() {
//        return "upload";
//    }

    @ResponseBody
    @PostMapping("/toUploadBlog")
    public ResponseResult<?> toUploadBlogPost(MultipartFile file) {
        log.info("=========>文件上传");
        Map<String,String> map = new HashMap<>();
        try {
            if (null != file) {
                String filename = file.getOriginalFilename();
                if (!"".equals(filename.trim())) {
                    File newFile = new File(filename);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    os.close();
                    file.transferTo(newFile);
                    //上传到OSS
                    String uploadUrl = "http://"+aliyunOSSUtil.upload(newFile);
                    map.put("uploadUrl",uploadUrl);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return new ResponseResult<Object>(200,"上传成功",map);
    }

    @GetMapping("/getObjectList")
    @ResponseBody
    public ResponseResult<List<String>> getObjectList() {
        String bucketName = constantProperties.getBucketname();
//        System.out.println(bucketName);
        List<String> objectList = aliyunOSSUtil.getObjectList(bucketName);
        return new ResponseResult<>(200,"获取成功",objectList);
    }

    @GetMapping("/delete")
    @ResponseBody
    public ResponseResult<String> deleteBlog(@RequestParam("key")String key){
        aliyunOSSUtil.deleteBlog(key);
        return new ResponseResult<>(200,"删除成功");
    }
}